<?php
class HeaderForm extends Form
{
    function __construct()
    {
        Form::Form('HeaderForm');

        if (User::have_permit(ADMIN_LOGO)) {
            $this->link_css('style/aznet/ui.datepicker.css');
            $this->link_js('javascript/jquery/ui.datepicker.js');
        }

        if (User::is_login() && User::level()) {
            $this->link_header("<script>MM_preloadImages('style/images/newCart/icon_del.gif','style/images/newCart/Mua.png');</script>");
        }

        // session session_id()

        CGlobal::$cart_sess_id = isset($_COOKIE['cart_sess_id']) ? $_COOKIE['cart_sess_id'] : '';

        if (CGlobal::$cart_sess_id) {
            AZLib::my_setcookie('cart_sess_id', session_id(), time() + 3600 * 24 * 365);
        }
        $this->link_js(FOLDER_JS . 'jquery.min.js');
        $this->link_js(FOLDER_JS . 'jquery-ui.js');
        $this->link_js(FOLDER_JS . 'jcarousellite_1.0.1c4.js');
        $this->link_js(FOLDER_JS . 'ui/jquery.ui.core.js');
        $this->link_js(FOLDER_JS . 'ui/jquery.ui.widget.js');
        $this->link_js(FOLDER_JS . 'ui/jquery.ui.tabs.js');
        $this->link_js('static/lightbox/js/jquery.lightbox-0.5.js');
        $this->link_js('static/adgallery/jquery.ad-gallery.js');

        $this->link_css(FOLDER_CSS . 'menu.css@lang=vi-vn.css');
        $this->link_css(FOLDER_CSS . 'sanpham.css@lang=vi-vn.css');
        $this->link_css(FOLDER_CSS . 'style.css@lang=vi-vn.css');
        $this->link_css(FOLDER_CSS . 'style_new.css@lang=vi-vn.css');
        $this->link_css(FOLDER_CSS . 'tintuc.css@lang=vi-vn.css');
        $this->link_css(FOLDER_CSS . 'trangchu.css@lang=vi-vn.css');
        $this->link_css(FOLDER_CSS . 'custom.css');
        $this->link_css(FOLDER_CSS . 'home.css');
        $this->link_css(FOLDER_CSS . 'base/jquery.ui.all.css');
        $this->link_css('static/lightbox/css/jquery.lightbox-0.5.css');
        $this->link_css('static/adgallery/jquery.ad-gallery.css');
    }

    function draw()
    {
        global $display;

        AZLib::get_config();


        /*if (CGlobal::$curZone) {
            $zone_id = CGlobal::$curZone['id'];
        } else {
            $zone_id = 0;
        }*/

        $zid = (int)Url::get("zone_id", 0);
        $display->add('cur_page', AZNet::$page['name']);
        $display->add('ADMIN_LOGO', User::have_permit(ADMIN_LOGO));

        $in_detail_page = (AZNet::$page['name'] == 'item_detail');
        $topcats        = array();
        $pcats          = array();

        $stt  = 0;
        $stt2 = 0;

        foreach (CGlobal::$subCategories as $top_id => $sub_cats) {
            if (isset(CGlobal::$allCategories[$top_id]) && CGlobal::$allCategories[$top_id]['parent_id'] == 0) {
                $topcat = CGlobal::$allCategories[$top_id];

                if ($topcat['status'] == "HOME") {
                    $topcat['name'] = $topcat['brief_name'];

                    if (count($sub_cats) > 7) {
                        $stt2++;
                    }
                    $topcat['left'] = "-" . (($stt2 - 1) * 30 + 10) . "px";


                    $topcat['url'] = WEB_DIR . "c{$topcat['id']}/{$topcat['ebname']}";

                    $topcat['selected']  = (int)(CGlobal::$curMainCat && CGlobal::$curMainCat['id'] == $topcat['id']);
                    $topcat['selected2'] = 0;

                    if ($topcat['selected']) {
                        if ($sub_cats) {
                            $topcat['class'] = "hm_item_list_sub";
                        } else {
                            $topcat['class'] = "hm_item_seleted";
                        }
                    } else {
                        $topcat['class'] = "hm_item";
                    }

                    if ($sub_cats) {
                        $topcat['subs'] = array();

                        $num_sub = 0;

                        foreach ($sub_cats as $sid => $subcat) {
                            if ($subcat['status'] != "HIDE") {
                                $subcat['url'] = WEB_DIR . "c{$subcat['id']}/{$topcat['ebname']}-{$subcat['ebname']}"; //$subcat['name'] 		= $subcat['brief_name'];

                                if (CGlobal::$curLevel2Cat && CGlobal::$curLevel2Cat['id'] == $subcat['id']) //Chọn danh mục cấp 2
                                {
                                    $topcat['selected2'] = 1;

                                    $topcat['class'] = "hm_item_seleted";
                                    $subcat['class'] = "class='sub_seleted'";
                                }

                                $topcat['subs'][$sid] = $subcat;

                                $num_sub++;
                            }
                        }

                        if ($topcat['selected'] && !$topcat['selected2']) {
                            $max_per_col = ceil($num_sub / 5);

                            if ($max_per_col <= 0) $max_per_col = 1;

                            $display->add('max_per_col', $max_per_col);
                            $display->add('subcat_items', $topcat['subs']);
                        }
                    }

                    $topcats[$top_id] = $topcat;

                    // if($stt++ >= 6)
                    //break;
                }
            }
        }

        $display->add('topcats', $topcats);

        $display->add('web_dir', WEB_DIR);
        $display->add('DATA_PATH', DATA_PATH);

        //Load Logo
        //$test_time = mktime(0,0,0,11,26,2010);
        AZLib::getWebsiteLogo();
        if ((CGlobal::$websiteLogo !== FALSE) && isset(CGlobal::$websiteLogo['current']['expired']) && CGlobal::$websiteLogo['current']['expired'] && (CGlobal::$websiteLogo['current']['expired'] < TIME_NOW)) {
            //  Nếu Logo đang sử dụng đã hết hạn, lấy Logo còn hạn hoặc lấy Logo mặc định
            AZLib::getWebsiteLogo(1);
        }
        $display->add('logo', CGlobal::$websiteLogo['current']);
        $display->add('logos', CGlobal::$websiteLogo['logos']);

        //Top menu
        if (!isset($_SESSION['is_load_page_first'])) {
            $_SESSION['is_load_page_first'] = 0;
        }
        $display->add('url_root', WEB_ROOT);

        if (!User::is_login()) {
            $num_mess = 0;
        } else {
            $num_mess = (User::$current->data['total_pm'] > 0) ? User::$current->data['total_pm'] : 0;
        }

        if (User::id()) {
            $display->add('user_id', User::id());

            $user_name = User::$current->data['user_name'];
            $display->add('user_name', $user_name);
        }

        $referer_login_url   = '';
        $yahoo_open_id_href  = '';
        $google_open_id_href = '';

        if (isset($_SESSION['openid_url']) && ($_SESSION['user_id'] != 0)) {
            $display->add('show_openid', FALSE);
        } elseif (!User::is_az_team()) {
            AZLib::check_uri();
            $referer_login_url = base64_encode(CGlobal::$query_string);

            $yahoo_open_id_href  = OID_URL . 'index.html?openid_identifier=http://me.yahoo.com/&long_redirect=' . base64_encode(CGlobal::$query_string);
            $google_open_id_href = OID_URL . 'index.html?openid_identifier=https://www.google.com/users/o8/id&long_redirect=' . base64_encode(CGlobal::$query_string);

            $display->add('show_openid', TRUE);
        }

        $display->add('OID_URL', $yahoo_open_id_href);
        $display->add('OID_URL_GOG', $google_open_id_href);
        $display->add('referer_login_url', $referer_login_url);
        $display->add('google_open_id_href', $google_open_id_href);
        $display->add('yahoo_open_id_href', $yahoo_open_id_href);
        $display->add('openid_on', OPENID_ON);
        $display->add('num_mess', $num_mess);

        $display->add('is_login', (int)User::is_login());
        $display->add('is_admin', (int)User::is_az_team());
        $display->add('is_admin_item', (int)User::have_permit(ADMIN_ITEM));
        $display->add('is_root', User::is_root());

        //End Top menu

        $display->add('category_id', CGlobal::$curCategory);
        $display->add('keywords', AZLib::cleanHtml(Url::get('keywords', '')));
        $display->add('not_error_page', (int)(AZNet::$page['name'] != 'error'));

        $display->add('is_load_page_first', $_SESSION['is_load_page_first']);

        // Tỷ giá
        AZLib::get_config();
        //$exchange = CGlobal::$configs['exchange']['conf_val'];
        //$display->add('exchange', number_format($exchange, 0, ',', '.'));
        // End Tỷ giá

        if ($_SESSION['is_load_page_first'] == 1) {
            $_SESSION['is_load_page_first'] = 0;
        }
        //End of top menu

        $curMainCat   = CGlobal::$curMainCat;
        $curLevel2Cat = CGlobal::$curLevel2Cat;


        //Cat menu
        $sub_menu = FALSE;

        $sub_menu = ($curMainCat && isset(CGlobal::$allCategories[$curMainCat['id']]) && isset(CGlobal::$subCategories[$curMainCat['id']]));

        $display->add('CURENT_TOP_CATID', (int)@$curMainCat['id']);
        $display->add('CURENT_LEVEL2_CATID', (int)@$curLevel2Cat['id']);
        $display->add('CURENT_CITY_ID', CGlobal::$curCity);
        $display->add('cur_page', Url::get('page'));
        $display->add('sub_menu', $sub_menu);
        $display->add('block_id', Module::$block_id);
        // System::debug($display->get_template_vars());
        //End Cat menu

        if (User::is_root()) {
            $display->add("DEBUG", DEBUG);
            $display->add("show_bug_url", AZRewrite::formatUrl(Url::build_all(array(), "ebug=" . (int)(!DEBUG))));
        }


        ################################################################################################################
        #Event config

        $event_on = @CGlobal::$configs['event_on']['conf_val'];
        $submit   = Url::get('submit', '');

        if (User::is_admin()) {
            if ($submit == 'Cập nhật') //Cập nhật event
            {
                $display->add('msg', $this->showFormErrorMessages(1));
            }

            $status_arr = array(0=> 'Tắt', 1=> 'Bật');
            $display->add('status_option', AZLib::getOption($status_arr, $event_on));
        }

        $display->add('event', $event_on);
        $display->add("data_path", DATA_PATH);


        #Event config
        ################################################################################################################


        ################################################################################################################
        #Search


        $search_catid = (int)Url::get('search_catid');


        $search_cat_arr = array(-1=> '--Tất cả danh mục--');

        foreach (CGlobal::$subCategories as $top_id => $sub_cats) {
            if (isset(CGlobal::$allCategories[$top_id]) && CGlobal::$allCategories[$top_id]['parent_id'] == 0) {
                $topcat = CGlobal::$allCategories[$top_id];

                if ($topcat['status'] != "HIDE") {
                    $search_cat_arr[$top_id] = $topcat['name'];

                    if ($sub_cats) {
                        foreach ($sub_cats as $sid => $subcat) {
                            if ($subcat['status'] != "HIDE") {
                                $search_cat_arr[$sid] = "-----" . $subcat['name'];
                            }
                        }
                    }
                }
            }
        }
        $display->add('search_cat_option', AZLib::getOption($search_cat_arr, $search_catid));
        #Search
        ################################################################################################################
        /*   System::debug($topcats);*/
        $cat_newss 		= array();
        $news_cat_id 	= Url::get('news_catid','id',0);

        AZLib::getNewsCats();

        $display->add('news_cat_id',$news_cat_id);

        if(CGlobal::$allNewsCategories)
        {
            foreach (CGlobal::$allNewsCategories as $news_cat)
            {
                if($news_cat['public'])
                {
                    $news_cat['url'] = URL::build('news_list',array('news_catid'=>$news_cat['id'],'azname'=>AZLib::safe_title($news_cat['name'])));

                    $cat_newss[$news_cat['id']] = $news_cat;
                }
            }
        }

        $display->add('cat_newss',$cat_newss);
        $display->output("Header");
        // $display->output("header_old");
    }

    function on_submit()
    {
        $submit     = Url::get('submit');
        $submitLogo = Url::get('submitLogo');

        if ($submit == 'Cập nhật') //Cập nhật event
        {
            if (User::is_admin()) {
                $status = (int)Url::get('status', 0);

                $b_background_file = DATA_PATH . "b_background.gif";

                if (isset($_FILES['b_background']) && $_FILES['b_background']['error'] == 0) {
                    $file_ext = strtolower(AZLib::getExtension($_FILES['b_background']['name']));
                    if (in_array($file_ext, array('.jpg', '.jpeg', '.png', '.gif'))) {
                        if (getimagesize($_FILES['b_background']['tmp_name'])) {
                            if (!move_uploaded_file($_FILES['b_background']['tmp_name'], $b_background_file)) {
                                $this->setFormError('b_background', 'Không up load được Body Background!');

                                return;
                            }
                        } else {
                            $this->setFormError('b_background', 'Sai định dạng Body Background!');

                            return;
                        }
                    } else {
                        $this->setFormError('b_background', 'Body Background chỉ chấp nhận các định dạng file .jpg, .jpeg, .gif, .png!');

                        return;
                    }
                }

                if (isset(CGlobal::$configs['event_on']))
                    DB::update('configs', array("conf_val"=> $status), "conf_key='event_on'");
                else
                    DB::insert('configs', array("conf_key"=> 'event_on', "conf_val"=> $status));

                AZLib::get_config(0, 1);
            }

            if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']) {
                $referer = $_SERVER['HTTP_REFERER'];
            } else {
                $referer = $_SERVER['REQUEST_URI'];
            }

            Url::redirect_url($referer);
        }

        if (User::have_permit(ADMIN_LOGO) && $submitLogo) {
            $id  = (int)Url::get('logoID', 0);
            $cmd = Url::get('logoCmd');

            if ($cmd == 'delete') {
                if ($id)
                    $record = DB::select('website_logo', 'id=' . $id);
                AZLib::ftp_image_delete_file($record['image'], $record['img_server']);
                $sql = 'delete FROM website_logo WHERE id = ' . $id;
                DB::query($sql);
                AZLib::getWebsiteLogo(1);
            } else {
                $logo       = array();
                $start_date = Url::get('logoStartDate', 0);
                $end_date   = Url::get('logoEndDate', 0);
                if ($id)
                    $logo = DB::fetch("SELECT * FROM website_logo WHERE id = $id");
                $logo['title'] = Url::get('logoTitle');
                if (!isset($logo['img_server']))
                    $logo['img_server'] = IMAGE_SERVER_NO;
                if (!$cmd) {
                    $logo['username'] = User::$current->data['user_name'];
                }
                if ($start_date) {
                    $date_arr = explode("-", $start_date);
                    if (isset($date_arr[0]) && isset($date_arr[1]) && isset($date_arr[2]))
                        $logo['start_date'] = mktime(0, 0, 0, (int)$date_arr[1], (int)$date_arr[0], (int)$date_arr[2]);
                } else
                    $logo['start_date'] = 0;

                if ($end_date) {
                    $date_arr = explode("-", $end_date);
                    if (isset($date_arr[0]) && isset($date_arr[1]) && isset($date_arr[2]))
                        $logo['end_date'] = mktime(23, 59, 59, (int)$date_arr[1], (int)$date_arr[0], (int)$date_arr[2]);
                } else
                    $logo['end_date'] = 0;

                if (Url::get('logoActive', 0)) {
                    DB::query("UPDATE website_logo SET status = 0");
                    $logo['status'] = 1;
                } else {
                    $logo['status'] = 0;
                }

                //Gen image unique name
                $img  = $_FILES['uploadLogo']['name'];
                $img  = explode('.', $img);
                $img  = array_pop($img);
                $mini = microtime(TRUE);
                $img  = $mini . '.' . $img;

                if ($_FILES['uploadLogo']['tmp_name']) {
                    if ($cmd == 'edit') { //sửa
                        AZLib::ftp_image_delete_file('logo/' . $img, $logo['img_server']);
                    }
                    if (AZLib::ftp_check_dir('logo/', TRUE, IMAGE_SERVER_NO)) {
                        $file_name  = 'logo/' . $img;
                        $sourceName = $_FILES['uploadLogo']['tmp_name'];
                        AZLib::ftp_image_put_file($file_name, $sourceName, IMAGE_SERVER_NO);
                        $logo['image'] = $file_name;
                    }
                }
                if (!$this->errNum && isset($logo['image']) && $logo['image']) {
                    if ($cmd == 'edit') {
                        DB::update('website_logo', $logo, 'id=' . $id);
                    } else {
                        $id = DB::insert('website_logo', $logo);
                    }
                    AZLib::getWebsiteLogo(1);
                }
            }
        }
    }
}

?>